package com.org.platform.support.error;

import com.org.platform.enums.HttpStatusEnum;
import com.org.platform.model.ResultModel;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@ControllerAdvice
@RestController
public class ErrorController  {

  @RequestMapping(value = {"/error/329"})
  public ResultModel page329(HttpServletRequest request) {
    return ResultModel.newFail(HttpStatusEnum.ERROR329.getCode(), HttpStatusEnum.ERROR329.getMessage());
  }

  @RequestMapping(value = { "/error/400" })
  public ResultModel page400(HttpServletRequest request){
    return ResultModel.newFail(HttpStatusEnum.ERROR400.getCode(),HttpStatusEnum.ERROR400.getMessage());
  }

  @RequestMapping(value = { "/error/401" })
  public ResultModel page401(HttpServletRequest request){
    return ResultModel.newFail(HttpStatusEnum.ERROR401.getCode(),HttpStatusEnum.ERROR401.getMessage());
  }

  @RequestMapping(value = { "/error/404" })
  public ResultModel page404(HttpServletRequest request){
    return ResultModel.newFail(HttpStatusEnum.ERROR404.getCode(),HttpStatusEnum.ERROR404.getMessage());
  }

  @RequestMapping(value = {"/error/429"})
  public ResultModel page429(HttpServletRequest request) {
    return ResultModel.newFail(HttpStatusEnum.ERROR429.getCode(), HttpStatusEnum.ERROR429.getMessage());
  }

  @RequestMapping(value = { "/error/500" })
  public ResultModel page500(HttpServletRequest request){
    return ResultModel.newFail(HttpStatusEnum.ERROR500.getCode(),HttpStatusEnum.ERROR500.getMessage());
  }

  @ExceptionHandler(value = Exception.class)
  public ResultModel errorHandler(HttpServletRequest request,Exception ex){
    log.error(ex.toString(),ex);
    return ResultModel.newFail();
  }

  @ExceptionHandler(value = MethodArgumentNotValidException.class)
  public ResultModel methodArgumentNotValidExceptionHandler(HttpServletRequest request,MethodArgumentNotValidException ex){
    BindingResult bindResult = ex.getBindingResult();
    String message = bindResult.getFieldError().getDefaultMessage();
    return ResultModel.newFail(message);
  }

}
